<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 300px;
            height: 400px;
            overflow-y: auto;
            border: 1px solid #000;
        }

        .list{
            width: 100%;
            height: 40px;
            margin: 10px 0;
            background-color: aqua;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>
<body>
    <div id="app"></div>
</body>

<script src="../js/17.0.1/react.development.js"></script>
<script src="../js/17.0.1/react-dom.development.js"></script>
<script src="../js/17.0.1/babel.min.js"></script>

<script type="text/babel">


    class MyComponent extends React.Component{
        
        state = {
            listArr: ['消息2', '消息1']
        }

        componentDidMount(){
            let count = this.state.listArr.length + 1;
            setInterval( ()=> {
                let str = '消息' + count;
                count += 1;
                this.setState({ listArr: [ str , ...this.state.listArr ] })
            }, 1000 )
        }


        getSnapshotBeforeUpdate( prevProps, prevState ){
            return this.refs.listBox.scrollHeight
        }

        componentDidUpdate  ( prevProps, prevState, height ){
            console.log( height );
            this.refs.listBox.scrollTop += this.refs.listBox.scrollHeight - height
        }


        render(){
            return (
                <div className="box" ref='listBox'>
                    {
                        this.state.listArr.map( ( item, index ) => {
                            return <div className="list" key={index}>{item}</div>
                        } )
                    }
                </div>
            )
        }
    }

    ReactDOM.render( <MyComponent/>, document.getElementById('app'))

</script>

</html>